package cn.ichiva.conf;

import cn.ichiva.common.DefaultException;
import cn.ichiva.common.HttpException;
import cn.ichiva.common.Error;
import cn.ichiva.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * 统一错误处理
 */
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    private final static Logger log = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(value = DefaultException.class)
    public R<?> defaultException(DefaultException e){
        log.error("default error",e);
        return R.error(e.getError());
    }

    @ExceptionHandler(value = HttpException.class)
    public R<?> httpException(HttpException e){
        log.error("http error",e);
        return R.error(e.getHttpStatus());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<?> methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("参数校验出错",e);
        return R.error(Error.ARG_VALID.getCode(),e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(value = HttpMessageConversionException.class)
    public R<?> methodArgumentNotValidException(HttpMessageConversionException e){
        log.error("JSON参数出错",e);
        return R.error(Error.ARG_VALID);
    }

    @ExceptionHandler(value =Exception.class)
    public R<?> exception(Exception e){
        log.error("未处理错误",e);
        return R.error(Error.OTHER);
    }
}